﻿using System;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using micsun.Logic;

namespace tmsWeb
{
    public enum RedirectType
    {
        ViewPage, FormPage, CustomPage
    }
    /// <summary>
    /// Transfer 的摘要说明。
    /// </summary>
    public partial class Transfer : micsun.Web.NonSecurityPage
    {
        public const string Param_Action = "a";
        public const string Param_View = "v";
        public const string Param_Form = "f";
        public const string Param_Url = "u";
        public const string Param_Transfer = "trans";
        public const string Param_TransParm = "p";
        public const string Param_Key = "key";
        public const string Param_ReturnUrl = "rui";
        public const string Param_TransferToWhenSuccess = "ts";
        public const string Param_Report = "r";
        public const string Param_BackView = "bv";

        protected override bool AllowScroll
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 是否处理显示信息
        /// </summary>
        protected override bool HandleMessage
        {
            get
            {
                return false;
            }
        }

        #region redirect parameter add、get、store
        /// <summary>
        /// 增加要通过Redirect传递的参数
        /// </summary>
        /// <param name="name">参数名</param>
        /// <param name="value">参数值（该值请不要调用UrlEncode，此方法内部会调用）</param>
        public static void AddRedirectParameters(string name, string value)
        {
            if (name != null && name != string.Empty && value != null)
            {
                string stored = GetStoredRedirectedParameters();
                if (stored != null && stored != string.Empty)
                    stored += "&";
                stored += name + "=" + HttpUtility.UrlEncode(value);
                SaveStoredRedirectedParameters(stored);
            }
        }
        /// <summary>
        /// 增加要通过Redirect传递的参数
        /// </summary>
        /// <param name="parameters">组合好的参数与值（值请自行调用UrlEncode方法）</param>
        public static void AddRedirectParameters(string parameters)
        {
            //如果第一个字符为"?"或"&"，则去掉它
            if (parameters.StartsWith("?") || parameters.StartsWith("&"))
                parameters = parameters.Remove(0, 1);
            if (parameters != null && parameters != string.Empty)
            {
                string stored = GetStoredRedirectedParameters();
                if (stored != null && stored != string.Empty)
                    stored += "&";
                stored += parameters;
                SaveStoredRedirectedParameters(stored);
            }
        }
        /// <summary>
        /// 清除掉已经保存的所有Redirect的参数
        /// </summary>
        public static void ClearStoredRedirectParameters()
        {
            SaveStoredRedirectedParameters(string.Empty);
        }

        private static string GetStoredRedirectedParameters()
        {
            return ParameterStock;
        }

        private void InitializeComponent()
        {

        }

        private static void SaveStoredRedirectedParameters(string stored)
        {
            ParameterStock = stored;
        }

        const string ParameterStockKey = "__parameterStock";
        private static string ParameterStock
        {
            get
            {
                object o = System.Runtime.Remoting.Messaging.CallContext.GetData(ParameterStockKey);

                return (string)o;
            }
            set
            {
                System.Runtime.Remoting.Messaging.CallContext.SetData(ParameterStockKey, value);
            }
        }
        #endregion

        #region const url defines
        public static string ErrorPageUrl
        {
            get
            {
                return GetUrlRoot() + "error.aspx";
            }
        }
        public static string TransferUrl
        {
            get
            {
                return micsun.Web.ApplicationBase.GetUrlRoot() + "Transfer.aspx";
            }
        }




        public static string GetUrlRoot()
        {
            return micsun.Web.ApplicationBase.GetUrlRoot();
        }

        public static string ImageRootPath
        {
            get
            {
                return micsun.Web.ApplicationBase.GetUrlRoot() + "App_Themes/default/images/";
            }
        }
        #endregion

        #region Static Methods
        public static void ShowErrorPage(string message)
        {
            HttpContext.Current.Response.Redirect(ErrorPageUrl + "?err=" + HttpUtility.UrlEncode(message), true);
        }

        public static void ShowErrorPage(Exception ex)
        {
            ShowErrorPage(ex.Message);
        }


        #endregion

        #region redirect methods
        public static void Redirect(string url)
        {
            Redirect(url, true);
        }
        public static void Redirect(string url, string Traget)
        {
            Redirect(url, true, Traget);
        }

        public static void Redirect(string url, bool showTransfer)
        {

            RedirectInternal(url, showTransfer, Param_Url, "_self");
        }

        private static void Redirect(string url, bool showTransfer, string Traget)
        {

            RedirectInternal(url, showTransfer, Param_Url, Traget);
        }
        public static void RedirectToNamedPage(string name, bool showTransfer)
        {
            string url = GetNamedPageUrl(name);

            if (showTransfer)
            {
                RedirectInternal(url, showTransfer, Param_Url, "_top");
            }
            else
            {
                CombinUrl(ref url);
                HttpContext.Current.Response.Redirect(url, true);
            }
        }

        public static void RedirectToNamedPage(string name)
        {
            RedirectToNamedPage(name, true);
        }

        public static string GetNamedPageUrl(string name)
        {
            string url = (string)micsunConfiguration.NamedPage[name];
            if (url == null)
                return GetUrlRoot();
            else
                return GetUrlRoot() + url;
        }

        private static void CombinUrl(ref string url)
        {
            string storedParameters = GetStoredRedirectedParameters();
            char c = '?';
            if (url == null) url = string.Empty;
            if (url.IndexOf(c) != -1)
                c = '&';

            if (storedParameters != null && storedParameters != string.Empty)
                url += c + storedParameters;
        }

        private static void RedirectInternal(string url, bool showTransfer, string type, string Traget)
        {
            CombinUrl(ref url);

            if (!showTransfer)
                HttpContext.Current.Response.Redirect(url, true);
            else
            {
                StringBuilder builder = new StringBuilder();

                builder.Append(TransferUrl)
                    .Append("?")
                    .Append(Param_Transfer)
                    .Append("=")
                    .Append(type)
                    .Append("&")
                    .Append(type)
                    .Append("=")
                    .Append(HttpUtility.UrlEncode(url))
                    .Append("&")
                    .Append("Traget")
                    .Append("=")
                    .Append(Traget);

                HttpContext.Current.Response.Redirect(builder.ToString(), true);
            }
        }
        #endregion

        protected override void OnInit(System.EventArgs e)
        {
            ParseTransferInformation();
        }

        private string _transTo;
        protected string TransferTo
        {
            get
            {
                return _transTo;
            }
        }

        private string _traget = "_self";
        protected string Target
        {
            get
            {
                return _traget;
            }
        }
        private ArrayList _parmList = new ArrayList();

        protected string GetFormItems()
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < _parmList.Count; i++)
            {
                DictionaryEntry e = (DictionaryEntry)_parmList[i];
                builder.Append("<input type='hidden' name='")
                    .Append(HttpUtility.HtmlEncode(e.Key.ToString()))
                    .Append("' value='")
                    .Append(HttpUtility.HtmlEncode(e.Value.ToString()))
                    .Append("'>");
            }
            return builder.ToString();
        }


        public void ParseTransferInformation()
        {
            if (Request.Params["Traget"] != null)
            {
                _traget = Request.Params["Traget"].ToString();
            }

            if (Request.Params[Param_TransParm] != null)
            {
                AddRedirectParameters(HttpUtility.UrlDecode(Request.Params[Param_TransParm]));
            }
            if (Request.Params[Param_Transfer] != null)
            {
                switch (Request.Params[Param_Transfer].ToLower())
                {
                    case "u":
                        if (Request.Params[Param_Url] == null)
                            _transTo = GetUrlRoot();
                        else
                            _transTo = Request.Params[Param_Url];
                        break;
                }

                _transTo = _transTo.Replace("?", "&");
                if (_transTo.IndexOf('&') != -1)
                {
                    string[] values = _transTo.Split('&');
                    _transTo = values[0];

                    for (int i = 1; i < values.Length; i++)
                    {
                        string[] p = values[i].Split('=');
                        if (p.Length != 2)
                            continue;
                        _parmList.Add(new DictionaryEntry(p[0], Server.UrlDecode(p[1])));
                    }
                }

                //				for( int i=0;i<Request.QueryString.Count;i++ ) 
                //				{
                //					string key = Request.QueryString.GetKey(i);
                //					if( string.Compare(key,Param_Transfer,true)!=0&&string.Compare(key,Param_Url,true)!=0 )			
                //						_parmList.Add( new DictionaryEntry( Request.QueryString.GetKey(i),Request.QueryString[i] ) );
                //				}
            }
            else
                ShowErrorPage("Cann't parse your request");
        }

        protected void Page_Load(object sender, System.EventArgs e)
        {

        }

    }
}
